<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <!-- <a-col :span="12">
          <a-form-item label="供应商编号" v-bind="validateInfos.supplierNo">
            <a-input v-model:value="formData.supplierNo" placeholder="请输入供应商编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="供应商名称" v-bind="validateInfos.supplierName">
            <a-input v-model:value="formData.supplierName" placeholder="请输入供应商名称" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="社会信用代码"  allowClear>
            <a-input v-model:value="formData.socialCreditCode" placeholder="请输入社会信用代码" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="服务开始时间" v-bind="validateInfos.serviceStartDate">
		        <a-date-picker placeholder="请选择服务开始时间" v-model:value="formData.serviceStartDate" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="服务结束时间" v-bind="validateInfos.serviceEndDate">
		        <a-date-picker placeholder="请选择服务结束时间" v-model:value="formData.serviceEndDate" value-format="YYYY-MM-DD"  style="width: 100%" :disabled="disabled" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人" v-bind="validateInfos.supplierOwner">
            <a-input v-model:value="formData.supplierOwner" placeholder="请输入联系人" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="电话" v-bind="validateInfos.mobile">
            <a-input v-model:value="formData.mobile" placeholder="请输入电话" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱" v-bind="validateInfos.email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="公司地址">
            <a-input v-model:value="formData.address" placeholder="请输入公司地址" :disabled="disabled" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="供应商介绍" v-bind="validateInfos.supplierDesc">
	          <a-textarea v-model:value="formData.supplierDesc" :rows="4" placeholder="请输入供应商介绍" :disabled="disabled" style="height:55px"  allowClear/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="负责人" key="supplierContract" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="supplierContractTableRef"
          :loading="supplierContractTable.loading"
          :columns="supplierContractTable.columns"
          :dataSource="supplierContractTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="岗位列表" key="supplierPosition" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="supplierPositionTableRef"
          :loading="supplierPositionTable.loading"
          :columns="supplierPositionTable.columns"
          :dataSource="supplierPositionTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { querySupplierContractListByMainId, querySupplierPositionListByMainId, queryDataById, saveOrUpdate } from '../SupplierManage.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {supplierContractColumns, supplierPositionColumns} from '../SupplierManage.data';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "SupplierManageForm",
    components:{
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const supplierContractTableRef = ref();
      const supplierContractTable = reactive<Record<string, any>>({
        loading: false,
        columns: supplierContractColumns,
        dataSource: []
      });
      const supplierPositionTableRef = ref();
      const supplierPositionTable = reactive<Record<string, any>>({
        loading: false,
        columns: supplierPositionColumns,
        dataSource: []
      });
      const activeKey = ref('supplierContract');
      const formData = reactive<Record<string, any>>({
        id: '',
        supplierNo: '',   
        supplierName: '',   
        socialCreditCode: '',   
        serviceStartDate: '',
        serviceEndDate: '',
        supplierOwner: '',
        mobile: '',
        email: '',
        address: '',   
        supplierDesc: '',   
      });

      //表单验证
      const validatorRules = reactive({
        supplierName: [{ required: true, message: '请输入供应商名称!'},],
        serviceStartDate: [{ required: true, message: '请输入服务开始时间!'},],
        serviceEndDate: [{ required: true, message: '请输入服务结束时间!'},],
        mobile: [{ required: true, message: '请输入电话!'},{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!'},],
        email: [{ required: true, message: '请输入邮箱!'},{ pattern: /^[A-Za-z0-9-._]+@[A-Za-z0-9-._]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,6})$/, message: '请输入正确的邮箱!'}],
        supplierOwner: [{ required: true, message: '请输入联系人!'},],
       
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        // labelCol: {xs: {span: 24}, sm: {span: 6}},
        // wrapperCol: {xs: {span: 24}, sm: {span: 12}},
        labelCol:{style: { width: '100px' }},
        wrapperCol: {span: 16},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        supplierContractTable.dataSource = [];
        supplierPositionTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const supplierContractDataList = await querySupplierContractListByMainId(row['id']);
        supplierContractTable.dataSource = [...supplierContractDataList];
        const supplierPositionDataList = await querySupplierPositionListByMainId(row['id']);
        supplierPositionTable.dataSource = [...supplierPositionDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'supplierContract': supplierContractTableRef,
        'supplierPosition': supplierPositionTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        supplierContractTableRef,
        supplierContractTable,
        supplierPositionTableRef,
        supplierPositionTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>